package com.shiku.imserver.common.tcp;

import com.shiku.imserver.common.packets.ImPacket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.tio.core.ChannelContext;
import org.tio.core.GroupContext;

public class TcpServerEncoder {
    public static ByteBuffer encode(TcpPacket tcpPacket, GroupContext groupContext, ChannelContext channelContext) {
        int bodyLen = 0;
        byte[] body = tcpPacket.getBytes();
        if (body != null) {
            bodyLen = body.length;
        }
        boolean isHasSynSeq = tcpPacket.getSynSeq().intValue() > 0;
        byte maskByte = ImPacket.encode4ByteLength(ImPacket.encodeHasSynSeq(ImPacket.encodeCompress(ImPacket.encodeEncrypt((byte) 1, true), true), isHasSynSeq), true);
        short cmdByte = tcpPacket.getCommand();
        tcpPacket.setVersion((byte) 1);
        tcpPacket.setMask(maskByte);
        int allLen = 2;
        if (isHasSynSeq) {
            allLen = 2 + 4;
        }
        ByteBuffer buffer = ByteBuffer.allocate(allLen + bodyLen + 6);
        buffer.order(groupContext == null ? ByteOrder.BIG_ENDIAN : groupContext.getByteOrder());
        buffer.put(tcpPacket.getVersion());
        buffer.put(tcpPacket.getMask());
        if (isHasSynSeq) {
            buffer.putInt(tcpPacket.getSynSeq().intValue());
        }
        buffer.putShort(cmdByte);
        buffer.putInt(bodyLen);
        buffer.put(body);
        return buffer;
    }
}
